import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, message, Row, Col, Button, Input, Tabs } from 'antd';
import router from 'umi/router';
import { urlParse } from '@/utils/utils';
import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import LocalPolicy from './LocalPolicy/Index'; // 引用组件

const FormItem = Form.Item;
const { TabPane } = Tabs;

@connect(({ localpolicy }) => ({
  localpolicy,
  contributorData: localpolicy.contributorData,
  pageData: localpolicy.pageData, // 减免政策列表数据
}))
@Form.create()
class BasicList extends PureComponent {
  state = {
    joinIdList: [],
    baseInfo: {},
    hshdRegFlag: '',
    selectedRows: [],
    selectedRowKeys: [],
    insLsPkgId: null, // 组合id
  };

  componentDidMount() {
    const { dispatch, location, pageData: { pagination } } = this.props;
    dispatch({
      type: 'localpolicy/getDictCode',
      payload: ['YES_NO_FLAG', 'BIZ_INS_TYPE', 'CARRY_RULE'],
    });
    const url = location.search;
    const { areaId, insLsPkgId, hshdRegFlag } = urlParse(url);
    this.setState({
      hshdRegFlag,
      insLsPkgId,
    });
    this.state.insLsPkgId = insLsPkgId;
    dispatch({
      type: 'localpolicy/getInsDetailList',
      payload: { insLsPkgId },
    }).then(res => {
      if (res.success) {
        this.setState({
          baseInfo: res.data,
        });
        if (Number(res.data.hshdRegFlag) === 1) {
          dispatch({
            type: 'localpolicy/getPaymentPerList',
            payload: { areaId },
          }).then(response => {
            if (response.success) {
              this.setState({
                joinIdList: response.data,
              });
            } else {
              message.warning(response.message || '服务端未知错误');
            }
            const paramet = {
              insLsPkgId: res.data.insLsPkgId,
              joinIdeId: response.data[0] ? response.data[0].ideId : '',
              type: '3',
            };
            // 获取该缴费人员下该险种下的所有信息
            dispatch({
              type: 'localpolicy/insuranceInformation',
              payload: paramet,
            });
            // 保存缴费人员id和组id
            dispatch({
              type: 'localpolicy/preservationId',
              payload: paramet,
            });
          });
        } else {
          const paramet = {
            insLsPkgId: res.data.insLsPkgId,
            type: '3',
          };
          // 获取该缴费人员下该险种下的所有信息
          dispatch({
            type: 'localpolicy/insuranceInformation',
            payload: paramet,
          });
          // 保存缴费人员id和组id
          dispatch({
            type: 'localpolicy/preservationId',
            payload: paramet,
          });
        }
      } else {
        message.warning(res.message || '服务端未知错误');
      }
    });
    this.getReliefPolicyList(pagination.current, pagination.pageSize, insLsPkgId);
  }

  // 返回
  prev = () => {
    router.goBack();
  };

  urlParse = () => {
    const { location } = this.props;
    const url = location.search;
    const obj = {};
    if (url.indexOf('?') !== -1) {
      const str = url.substr(1);
      const strs = str.split('&');
      strs.forEach(item => {
        obj[item.split('=')[0]] = unescape(item.split('=')[1]);
      });
    }
    return obj;
  };

  // 切换缴费人员类别
  ideTabChange = value => {
    const { dispatch, localpolicy } = this.props;
    dispatch({
      type: 'localpolicy/changeMessage',
      payload: { value },
    });
    const paramet = {
      insLsPkgId: localpolicy.groupId,
      joinIdeId: value,
      type: localpolicy.insuranceIds,
    };
    // 添加完以后获取该缴费人员下该险种下的所有信息
    dispatch({
      type: 'localpolicy/insuranceInformation',
      payload: paramet,
    });

    // 清空默认值
    dispatch({
      type: 'localpolicy/clearDefault',
      payload: {},
    });
  };

  // 获取减免政策列表数据
  getReliefPolicyList = (currentPage = 1, pageSize = 10, insLsPkgId) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'localpolicy/fetchReliefPolicy',
      payload: {
        pageArg: { currentPage, pageSize },
        insLsPkgId,
      },
    });
  }

  // 点击复选框
  handleSelectRows = (rows, rowKeys) => {
    this.setState({ selectedRows: rows, selectedRowKeys: rowKeys });
  };

  // 点击分页
  handleStandardTableChange = pagination => {
    const { insLsPkgId } = this.state;
    this.getReliefPolicyList(pagination.current, pagination.pageSize, insLsPkgId);
  };


  render() {
    const { joinIdList, hshdRegFlag, baseInfo, selectedRows, selectedRowKeys } = this.state;
    const { form, localpolicy, pageData } = this.props;
    const formItemLayout = {
      labelCol: { md: { span: 14 } },
      wrapperCol: { md: { span: 8 } },
    };
    const formItemLayout2 = {
      labelCol: { md: { span: 10 } },
      wrapperCol: { md: { span: 12 } },
    };
    const { getFieldDecorator } = form;
    // 减免政策表格
    const reliefPolicyColumns = [
      {
        title: '险种',
        dataIndex: 'typeName',
        render: val => (val && val) || '--',
      },
      {
        title: '企业类型',
        dataIndex: 'entpTypeName',
        render: val => (val && val) || '--',
      },
      {
        title: '减免时间段',
        dataIndex: 'remissionPeriod',
        render: (text, record) => (
          <span>
            {record.remisBeginYm && moment(record.remisBeginYm).format('YYYY-MM') || '--'}
            -
            {record.remisEndYm && moment(record.remisEndYm).format('YYYY-MM') || '--'}
          </span>
        )
      },
      {
        title: '企业应缴比例',
        dataIndex: 'corpProp',
        render: val => val === 0 ? '0%' : (val && `${val}%`) || '--',
      },
      {
        title: '添加时间',
        dataIndex: 'creTime',
        render: val => (val ? moment(val).format('YYYY-MM-DD HH:mm') : '--'),
      },
    ];
    return (
      <div>
        <PageHeaderWrapper />
        <Card style={{ marginTop: 12, marginLeft: 12, marginRight: 12 }}>
          <div style={{ marginTop: 22 }}>
            <Form onSubmit={this.handleSubmit}>
              <Row style={{ marginBottom: 50, padding: '0 40px' }}>
                <Col span={8}>
                  <FormItem {...formItemLayout2} label="组合名称">
                    {getFieldDecorator('insLsPkgName', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: baseInfo.insLsPkgName,
                    })(<Input placeholder="请输入" disabled />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem {...formItemLayout} label="是否区分缴费人员类别">
                    {getFieldDecorator('hshdRegFlagName', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: baseInfo.hshdRegFlagName,
                    })(<Input disabled />)}
                  </FormItem>
                </Col>
              </Row>
            </Form>
            <div>
              <div>
                <div style={{ margin: '20px 0' }}>
                  {Number(hshdRegFlag) === 1 ? (
                    <Tabs
                      defaultActiveKey={joinIdList[0] ? joinIdList[0].ideId : ''}
                      onChange={this.ideTabChange}
                      type="card"
                    >
                      {joinIdList.map(value => (
                        <TabPane tab={value.ideName} key={value.ideId}>
                          <LocalPolicy
                            {...this.props}
                            isprovidentFund={1}
                            viewDataMessage={localpolicy.viewDataMessage}
                            insureArr={localpolicy.insureArr}
                            isaddBtn={2}
                            insuranceInformationData={localpolicy.insuranceInformationData}
                          />
                        </TabPane>
                      ))}
                    </Tabs>
                  ) : (
                    <LocalPolicy
                      {...this.props}
                      isprovidentFund={1}
                      viewDataMessage={localpolicy.viewDataMessage}
                      insureArr={localpolicy.insureArr}
                      isaddBtn={2}
                      insuranceInformationData={localpolicy.insuranceInformationData}
                    />
                  )}
                </div>
              </div>
            </div>
            {/* 减免政策 */}
            <div style={{ marginTop: 20 }}>
              <h3
                style={{
                  fontSize: 14,
                  height: '54px',
                  lineHeight: '54px',
                  backgroundColor: 'rgba(250, 250, 250)',
                  padding: '0 16px',
                }}
              >
                减免政策
              </h3>
              <StandardTable
                style={{ margin: '5px 0 20px 0' }}
                selectedRows={selectedRows}
                selectedRowKeys={selectedRowKeys}
                data={pageData}
                columns={reliefPolicyColumns}
                rowKey={record => record.remisId}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              />
            </div>
            <p style={{ textAlign: 'center' }}>
              <Button style={{ marginLeft: 30 }} onClick={() => this.prev()}>
                返回
              </Button>
            </p>
          </div>
        </Card>
      </div>
    );
  }
}
const BasicListFrom = Form.create()(BasicList);
export default BasicListFrom;
